<template>
  <div class="dashboard-container">
    <el-card class="header-card">
      <div class="page-header">
        <i class="el-icon-office-building"></i>
        <span class="page-title">仓储货位统计</span>
      </div>
    </el-card>
    <!-- 概览统计卡片 -->
    <el-row :gutter="20" class="statistics-row">
      <el-col :xs="24" :sm="12" :md="8">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <i class="el-icon-box stat-icon total"></i>
            <el-statistic title="总货位数">
              <template slot="formatter">
                {{ this.topList[0] && this.topList[0].totalUnitNum }}
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="8">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <i class="el-icon-box stat-icon used"></i>
            <el-statistic title="已使用货位">
              <template slot="formatter">
                {{ this.topList[0] && this.topList[0].usedUnitNum }}
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="8">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <i class="el-icon-box stat-icon available"></i>
            <el-statistic title="闲置货位">
              <template slot="formatter">
                {{ this.topList[0] && this.topList[0].unusedUnitNum }}
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-card class="queryBox">
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="leftBox">
            <div class="title">
              <div class="blueLine">
                仓库
              </div>
            </div>
            <div class="right">
              <el-select v-model="formList.stoId" placeholder="请选择仓库" clearable :style="{ width: '100%' }"
                         filterable>
                <el-option v-for="item in warehousesList" :key="item.stoId" :label="item.stoName" :value="item.stoId"/>
              </el-select>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="leftBox">
            <div class="title">
              <div class="blueLine">
                货架类型
              </div>
            </div>
            <div class="right">
              <el-select v-model="formList.type" placeholder="货架类型" clearable :style="{ width: '100%' }"
                         filterable>
                <el-option v-for="item in areaList" :key="item.stoId" :label="item.name" :value="item.tag"/>
              </el-select>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="leftBox">
            <div class="title">
              <div class="blueLine">
                查询条件
              </div>
            </div>
            <div style="text-align: center">
              <el-button type="primary" @click="getUnitList">查询</el-button>
              <el-button type="danger" @click="resetAll">重置</el-button>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <!-- 可视化统计 -->
    <el-card class="detail-card">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card shadow="never">
            <div ref="utilizationChart" style="width: 100%; height: 300px;"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="never">
            <div ref="categoryChart" style="width: 100%; height: 300px;"></div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
    <!-- 详细统计区域 -->
    <el-card class="detail-card">
      <el-tabs v-model="activeTab" @tab-click="handleTab">
        <el-tab-pane label="按仓库统计" name="first">
          <el-table height="450px" border :data="wareList" style="width: 100%" :span-method="objectSpanMethod">
            <el-table-column prop="warehouseName" label="仓库名称" align="center">
              <template #default="{row}">
                {{ row.warehouseName || 'N/A' }}
              </template>
            </el-table-column>
            <el-table-column prop="unitType" label="货位类型" align="center">
              <template #default="{row}">
                {{ row.unitType || 'N/A' }}
              </template>
            </el-table-column>
            <el-table-column label="货位数量" align="center">
              <template #default="{ row }">
                <el-tag type="success" style="margin-right: 10px">已使用:{{ row.usedUnitNum }}</el-tag>
                <el-tag type="danger">未使用:{{ row.unUsedUnitNum }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="按分类统计" name="secord">
          <el-table height="450px" :data="wareTypeList" border style="width: 100%" :span-method="objectSpanMethod">
            <el-table-column prop="gubFlag" label="货位类型" align="center">
              <template #default="{row}">
                {{ row.gubFlag || 'N/A' }}
              </template>
            </el-table-column>
            <el-table-column label="货位数量" align="center">
              <template #default="{ row }">
                <el-tag style="margin-right: 10px" type="success">已使用:{{ row.usedUnitNum }}</el-tag>
                <el-tag type="danger">未使用:{{ row.unUsedUnitNum }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="使用率" align="center">
              <template #default="{ row }">
                <span style="margin-right: 10px">已使用:{{ (row.usedRate).toFixed(2) }}%</span>
                <span>未使用:{{ (row.unUsedRate).toFixed(2) }}%</span>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import {
  basicStoShelf, //获取货架类型
} from "@/api/index/warehouse";
import {
  getAllWarehouseList,
} from "@/api/index/yxl";
import {
  wmsReportUnitStatistic //获取统计数量
} from '@/api/report/allNews'

export default {
  data() {
    return {
      topList: [],
      wareList: [], //仓储明细表
      wareTypeList: [], //仓库类型明细表
      formList: {
        wareHouseId: '',
      },
      areaList: [], //货架类型
      warehousesList: [], //仓库下拉
      activeTab: 'first',
      utilizationChart: null,
      categoryChart: null,
      spanMap: {
        warehouseName: [],
        unitType: []
      }
    }
  },
  created() {
    this.getUnitList(); //获取参数
    this.getWareList();
    this.getArea(); //获取货架类型
  },
  methods: {
    //重置
    resetAll(){
      this.formList = {
        stoId: '',
        type:''
      }
      this.getUnitList(); //获取参数
    },
    //获取仓库
    getWareList() {
      getAllWarehouseList().then(res => {
        this.warehousesList = res.data;
      })
    },
    handleTab(tab) {
      if (tab.name === 'first') {
        if (this.wareList && this.wareList.length > 0) {
          // 确保数据已按仓库名称和货位类型排序
          this.wareList.sort((a, b) => {
            return (a.warehouseName || '').localeCompare(b.warehouseName || '') ||
              (a.unitType || '').localeCompare(b.unitType || '');
          });
          this.calculateWarehouseSpans();
        } else {
          this.spanMap = {
            warehouseName: [1],
            unitType: [1]
          };
        }
      }
    },

    calculateWarehouseSpans() {
      const spanMap = {
        warehouseName: [],
        unitType: []
      };

      // 计算仓库名称合并规则
      this.calculateSingleSpan(spanMap.warehouseName, this.wareList, 'warehouseName');

      this.spanMap = spanMap;
    },
    calculateSingleSpan(result, data, field) {
      if (!data || data.length === 0) {
        result.push(1);
        return;
      }

      let pos = 0;
      for (let i = 0; i < data.length; i++) {
        if (i === 0) {
          result.push(1);
          pos = 0;
        } else {
          if (data[i][field] === data[i - 1][field]) {
            result[pos] += 1;
            result.push(0);
          } else {
            result.push(1);
            pos = i;
          }
        }
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (!this.spanMap) {
        return { rowspan: 1, colspan: 1 };
      }

      if (this.activeTab === 'first') {
        if (columnIndex === 0) {
          // 仓库名称列合并
          const rowspan = this.spanMap.warehouseName[rowIndex] || 0;
          return { rowspan, colspan: rowspan > 0 ? 1 : 0 };
        } else if (columnIndex === 1) {
          // 货位类型列 - 只在相同仓库内合并
          if (rowIndex > 0 &&
            this.wareList[rowIndex].warehouseName === this.wareList[rowIndex - 1].warehouseName &&
            this.wareList[rowIndex].unitType === this.wareList[rowIndex - 1].unitType) {
            return { rowspan: 0, colspan: 0 };
          }

          let count = 1;
          for (let i = rowIndex + 1; i < this.wareList.length; i++) {
            if (this.wareList[i].warehouseName === row.warehouseName &&
              this.wareList[i].unitType === row.unitType) {
              count++;
            } else {
              break;
            }
          }
          return { rowspan: count, colspan: 1 };
        }
      }
      return { rowspan: 1, colspan: 1 };
    },
    //获取货位数据
    getUnitList() {
      wmsReportUnitStatistic(this.formList).then(res => {
        this.topList = res.data.type || [];
        this.wareList = res.data.type2 || []; //仓储明细表
        this.wareTypeList = res.data.type1 || []; //仓库类型明细表
        this.handleTab({
          name: this.activeTab
        });
        this.initCharts();
      }).catch(error => {
        this.wareList = [];
        this.wareTypeList = [];
        this.handleTab({
          name: this.activeTab
        });
        this.initCharts();
      });
    },
    initCharts() {
      this.$nextTick(() => {
        this.initUtilizationChart();
        this.initCategoryChart();
      });
    },
    //获取货位编码
    getArea() {
      basicStoShelf().then(res => {
        this.areaList = res.rows || [];
      }).catch(error => {
        console.error('获取货位类型失败:', error);
        this.areaList = [];
      });
    },

    //切换仓库
    getWareHouse(val) {
      this.getUnitList(); // 重新加载数据
    },
    // 柱状图（分组展示）
    initCategoryChart() {
      if (!this.$refs.categoryChart) return;

      if (this.categoryChart) {
        this.categoryChart.dispose();
      }

      this.categoryChart = echarts.init(this.$refs.categoryChart);

      const categories = [];
      const usedData = [];
      const unusedData = [];

      this.wareTypeList.forEach(item => {
        categories.push(item.gubFlag || '未知类型');
        usedData.push(item.usedUnitNum || 0);
        unusedData.push(item.unUsedUnitNum || 0);
      });

      const option = {
        title: {
          text: '货位类型统计',
          left: 'center',
          textStyle: {color: '#333', fontSize: 16, fontWeight: 'bold'}
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {type: 'shadow'}
        },
        legend: {
          data: ['已使用', '闲置'],
          right: 10,
          top: 10,
          textStyle: {color: '#666'}
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: categories,
          axisLabel: {interval: 0, rotate: 30}
        },
        yAxis: {
          type: 'value',
          name: '数量',
          nameTextStyle: {padding: [0, 0, 0, 40]}
        },
        series: [
          {
            name: '已使用',
            type: 'bar',
            data: usedData,
            itemStyle: {color: '#67C23A'},
            label: {
              show: true,
              position: 'top'
            }
          },
          {
            name: '闲置',
            type: 'bar',
            data: unusedData,
            itemStyle: {color: '#F56C6C'},
            label: {
              show: true,
              position: 'top'
            }
          }
        ]
      };

      this.categoryChart.setOption(option);
      window.addEventListener('resize', () => {
        this.categoryChart.resize();
      });
    },

    initUtilizationChart() {
      if (!this.$refs.utilizationChart) return;

      if (this.utilizationChart) {
        this.utilizationChart.dispose();
      }

      this.utilizationChart = echarts.init(this.$refs.utilizationChart);

      const used = this.topList[0]?.usedUnitNum || 0;
      const unused = this.topList[0]?.unusedUnitNum || 0;
      const total = used + unused;

      const option = {
        title: {
          text: '货位利用率',
          left: 'center',
          top: 10,
          textStyle: {color: '#333', fontSize: 16, fontWeight: 'bold'}
        },
        tooltip: {
          trigger: 'item',
          formatter: params => {
            const percent = total > 0 ? (params.value / total * 100).toFixed(1) : 0;
            return `${params.name}<br/>数量: ${params.value}<br/>占比: ${percent}%`;
          }
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          data: ['已使用', '闲置'],
          textStyle: {color: '#666'}
        },
        series: [{
          name: '货位状态',
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['50%', '55%'], // 保持中间位置
          avoidLabelOverlap: true,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
            formatter: params => {
              const percent = total > 0 ? (params.value / total * 100).toFixed(1) : 0;
              return `${params.name}\n${params.value} (${percent}%)`;
            }
          },
          // 关键：让线条变斜
          labelLine: {
            show: true,
            length: 15,   // 第一段线的长度
            length2: 20,  // 第二段线的长度
            smooth: 0.3   // 设置为弧线/斜线 (0 是直角折线，1 是完全圆弧)
          },
          data: [
            {value: used, name: '已使用', itemStyle: {color: '#67C23A'}},
            {value: unused, name: '闲置', itemStyle: {color: '#F56C6C'}}
          ]
        }]
      };

      this.utilizationChart.setOption(option);
      window.addEventListener('resize', () => {
        this.utilizationChart.resize();
      });
    }


  },
  beforeDestroy() {
    // 组件销毁前移除事件监听
    window.removeEventListener('resize', () => {
      this.utilizationChart?.resize();
      this.categoryChart?.resize();
    });
    this.utilizationChart?.dispose();
    this.categoryChart?.dispose();
  }
}
</script>

<style scoped lang="scss">
.queryBox {
  ::v-deep .el-card__body {
    justify-content: space-evenly;
    display: flex;
  }

  .el-row {
    width: 100%;
  }
}

.dashboard-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.page-header {
  display: flex;
  align-items: center;
  font-size: 18px;
}

.page-title {
  margin-left: 10px;
  font-weight: bold;
}

.statistics-row {
  margin-bottom: 20px;
}

.stat-card {
  margin-bottom: 20px;
}

.stat-content {
  display: flex;
  align-items: center;
  overflow-x: auto;
}

.stat-icon {
  font-size: 36px;
  margin-right: 20px;
  padding: 15px;
  border-radius: 50%;
}

.stat-icon.total {
  color: #409EFF;
  background-color: #ecf5ff;
}

.stat-icon.used {
  color: #67C23A;
  background-color: #f0f9eb;
}

.stat-icon.available {
  color: #E6A23C;
  background-color: #fdf6ec;
}

.detail-card {
  margin-top: 20px;
}

::v-deep .el-statistic .con .number {
  font-size: 16px;
  padding: 0
}

.blueLine {
  display: flex;
  align-items: center;
}


.blueLine:before {
  content: "";
  background: #8cc5ff;
  display: block;
  width: 6px;
  height: 20px;
  margin-right: 10px;
}

.leftBox:nth-child(2n) .right {
  display: flex;
  align-items: center;
  justify-content: space-around;
}

.leftBox {
  margin-bottom: 10px;
  padding: 0 10px;
  height: 100px;
  border-radius: 10px;
  border: 1px solid #e1e1e1;
  box-shadow: 5px 5px 10px 0px rgba(0, 0, 0, 0.1);

  .title {
    justify-content: space-between;
    display: flex;
    align-items: center;
    color: #333333;
    font-weight: bold;
    padding: 10px 0px;
    font-size: 18px;
  }

  .right {
    display: flex;
    align-items: center;
    justify-content: space-evenly;
    font-size: 30px;
    color: #409EFF;
    font-weight: bold;
  }
}

.el-pagination {
  float: right;
  margin: 20px;
}
</style>
